package service

import (
	"fmt"
	"hy_808/configor"
	"hy_808/dao"
	"hy_808/di"
	"hy_808/global"
	"hy_808/protocol/hygprs"
	"hy_808/protocol/hygprs/packet"
	"hy_808/tcpx"
	"hy_808/util"
	"log"
	"strconv"
	"time"
)

func StartClientJoinHY() {
	opt := tcpx.Option{
		Name: "HYClient",
		Addr: configor.ConfigGlobal.HYSocketData.Addr,
		//ReadTimeout:    10,
		UseWriteBuffer: true,
		OnError: func(msg string, err error) {
			log.Println("连接失败", msg, err)
		},
		OnConnClosed: func(c *tcpx.Conn) {
			log.Println("OnConnClosed连接失败")
		},
		OnRetry: func(retry int, err error) {
			StartClientJoinHY()
			time.Sleep(2 * time.Second)
		},
		OnConnEstablished: func(c *tcpx.Conn) {
			//e := new(hygprs.InternalRegister)
			//e.Load(e.Make(hygprs.RoleJtt808Server))
			//fmt.Println("注册", hex.EncodeToString(e.Done()))
			p := packet.GenScheduleServerLogin(52)
			c.Send(tcpx.MakePackage(p.Data))
			fmt.Println("808模拟端登录")
		},
		ReceiveProvider: hygprs.ReceiveProvider(HyClient.OnReceive),
	}
	tcpx.StartClient(opt)
}

// 数据库查询车辆基础信息
func GetBusInfo() {
	db := di.TakeDB()
	logger := di.Logdot()
	var busList []dao.LSCHB
	err := db.Find(&busList, "SELECT * FROM LSCHB WHERE lschb_sfqy = 1")
	if err != nil {
		logger.Error("查询LSCHB数据异常")
		return
	}
	for _, bus := range busList {
		s := strconv.Itoa(bus.LSCHB_XLBH) + strconv.Itoa(bus.LSCHB_CH)
		phone := util.FillStr(s, "1", "left", 12)
		did := util.FillStr(s, "1", "right", 10) //终端编号
		dd := global.DeviceDBData{
			Phone:      phone,
			DeviceNo:   bus.LSCHB_CH,
			DeviceId:   did,
			LineNO:     bus.LSCHB_XLBH,
			PlateNo:    bus.LSCHB_CPH,
			Color:      configor.ConfigGlobal.DeviceInfo.Color,
			Model:      configor.ConfigGlobal.DeviceInfo.Model,
			ProvinceId: configor.ConfigGlobal.DeviceInfo.ProvinceId,
			CityId:     configor.ConfigGlobal.DeviceInfo.CityId,
			ProducerId: configor.ConfigGlobal.DeviceInfo.ProducerId,
		}
		global.DeviceDBDataMap.Store(bus.LSCHB_CH, dd)
	}
}

func SetDeviceBasic(line, bus int) global.DeviceDBData {
	s := strconv.Itoa(line) + strconv.Itoa(bus)
	dd := global.DeviceDBData{
		Phone:      util.FillStr(s, "1", "left", 12),
		DeviceNo:   bus,
		LineNO:     line,
		PlateNo:    "鲁A03124",
		Color:      configor.ConfigGlobal.DeviceInfo.Color,
		Model:      configor.ConfigGlobal.DeviceInfo.Model,
		ProvinceId: configor.ConfigGlobal.DeviceInfo.ProvinceId,
		CityId:     configor.ConfigGlobal.DeviceInfo.CityId,
		ProducerId: configor.ConfigGlobal.DeviceInfo.ProducerId,
	}
	global.DeviceDBDataMap.Store(bus, dd)
	return dd
}
